<?php


namespace app\api\service;


use think\Exception;

class AccessToken
{
    private $access_url;
    const ACCESS_TOKEN_CACHED_KEY = 'access';
    const ACCESS_TOKEN_EXPIRE_IN = 7000;

    public function __construct()
    {
        $url = config('wechat.access_token_url');
        $url = sprintf($url, config('wechat.app_id'), config('wechat.app_secret'));
        $this->access_url = $url;
    }

    public function get()
    {
        $token = $this->getFromCache();
        if(!$token){
            return $this->getFromServer();
        }else{
            return $token;
        }
    }

    private function getFromCache()
    {
        $token = cache(self::ACCESS_TOKEN_CACHED_KEY);
        if(!$token)
        {
            return null;
        }
        return $token;
    }

    private function getFromServer()
    {
        $token = curl_get($this->access_url);
        $token = json_decode($token, true);
        if(!$token){
            throw new Exception('获取AccessToken异常');
        }
        if(!empty($token['errcode'])){
            throw new Exception($token['errmsg']);
        }

        $this->saveToCache($token);
        return $token['access_token'];
    }

    private function saveToCache($token)
    {
        cache(self::ACCESS_TOKEN_CACHED_KEY, $token, self::ACCESS_TOKEN_EXPIRE_IN);
    }
}